package com.ztgf.sms.common;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/*
阿里短信服务配置
 */
@Component
public class GetALPostMsg {
    @Value(value = "${sms.al.posturl}")
    private String postUrl; //成都创信发送短信地址

    @Value(value = "${sms.al.accesskeyid}")
    private String accessKeyId; //accessKeyId

    @Value(value = "${sms.al.accesssecret}")
    private String accessSecret; //accessSecret

    @Value(value = "${sms.al.signname}")
    private String signName; //签名

    /**
     * 发送短信
     * @param mobile
     * @param modelCode
     * @param map
     * @return
     */
    public boolean SendMSM(String mobile, String modelCode, HashMap<String, String> map) throws Exception{
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        ObjectMapper mapper = new ObjectMapper();
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", modelCode);
        request.putQueryParameter("TemplateParam",  mapper.writeValueAsString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
            return response.getData().contains("OK");
        } catch (ServerException e) {
            e.printStackTrace();
            return false;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }
}




